package cn.springcloud.fix.demo.thread;

/**
 * https://www.cnblogs.com/hanganglin/articles/3517178.html
 * http://jiangzhengjun.iteye.com/blog/652269
 */
public class ThreadInterruptSample implements Runnable {

    public static void main(String[] args) throws InterruptedException {
        ThreadInterruptSample tis = new ThreadInterruptSample();
        System.out.println("程序开始执行....");
        Thread t = new Thread(tis);
        t.start();
        Thread.sleep(3000);
        System.out.println("主线程请求中断子线程....");
        t.interrupt();
        Thread.sleep(3000);
        System.out.println("主线程结束....");
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            long startTime = System.currentTimeMillis();
            System.out.println("run....");
            //间隔一秒循环判断线程是否被请求中断
            while (System.currentTimeMillis() - startTime < 1000) {
            }
        }
        //这里可以执行线程中断前的一些处理工作
        System.out.println("线程中断....");
    }
}